const mongoose = require('mongoose')
const UserSchema = mongoose.model('UserSchema')
const Router = require('koa-router')
const UserRouter = new Router()
UserRouter.post('/register', async ctx => {
  const { body } = ctx.request
  try {
    const res = await UserSchema.findOne({ userName: body.userName }).exec()
    if (res) {
      return ctx.body = {
        code: 500,
        msg: '用户名已经注册'
      }
    }
    const newUser = await new UserSchema(body).save()
    ctx.cookies.set('userId', newUser._id, {
      path: '/',
      httpOnly: false,
      overwrite: false,
      maxAge: 10 * 60 * 1000 //ms
    })
    
    ctx.body = {
      code: 200,
      msg: '注册成功'
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      msg: '注册失败'
    }
  }
})

UserRouter.post('/login', async ctx => {
  try {
    const { body } = ctx.request
    // 过滤掉密码字段
    const currentUser = await UserSchema.findOne({userName: body.userName, password: body.password}, { password: 0 }).exec()
    if (!currentUser) {
      return ctx.body = {
        code: 500,
        msg: '用户名或者密码不正确！'
      }
    }
    ctx.cookies.set('userId', currentUser._id, {
      path: '/',
      httpOnly: false,
      overwrite: false,
      maxAge: 10 * 60 * 1000 //ms
    })
    ctx.body = {
      code: 200,
      msg: '登录成功'
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      msg: '登录失败'
    }
  }
})

// 获取当前登录用户信息
UserRouter.get('/currentUser', async ctx => {
  try {
    const userCookie = ctx.cookies.get('userId');
    if (!userCookie) {
      return ctx.body = {
        code: 401,
        msg: '登录已过期',
      }
    }
    const currentUser = await UserSchema.findById(userCookie, { password: 0 }).exec();
    ctx.body = {
      code: 200,
      data: currentUser,
      msg: '获取成功'
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      msg: '获取失败'
    }
  }
})
// 获取相应的成员列表
UserRouter.get('/getMemberList', async ctx => {
  try {
    const { query: { type } } = ctx.request;
    const conditionType = type === 'genius' ? 'boss' : 'genius';
    const members = await UserSchema.find({ type: conditionType }, { password: 0 });
    ctx.body = {
      code: 200,
      msg: '获取成功',
      data: members
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      msg: '获取失败'
    }
  }
})
// 更新当前用户信息
UserRouter.put('/updateCurrentUser', async ctx => {
  try {
    const { body } = ctx.request;
    const userCookie = ctx.cookies.get('userId')
    await UserSchema.update({_id: userCookie}, { $set: body })
    ctx.body = {
      code: 200,
      msg: '更新成功'
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      msg: '更新失败'
    }
  }
})
// 登出
UserRouter.post('/logout', async ctx => {
  try {
    ctx.cookies.set('userId', undefined, {
      path: '/',
      httpOnly: false,
      overwrite: false,
      maxAge: -1
    })
    ctx.body = {
      code: 401,
      msg: '退出成功'
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      msg: '退出失败'
    }
  }
})
// 获取被发送者的信息
UserRouter.get('/getSendedUserInfo', async ctx => {
  try {
    const { query } = ctx.request
    const sendedUser = await UserSchema.findById(query.sendedId, { password: 0 }).exec()
    ctx.body = {
      code: 200,
      msg: '获取成功',
      data: sendedUser
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      msg: '获取失败'
    }
  }  
})
// 更新被发送者的信息
UserRouter.put('/updateSendedUserInfo', async ctx => {
  try {
    const { body } = ctx.request
    const { toUserId, chatMsg } = body
    await UserSchema.update({ _id: toUserId }, { $set: { chatMsg } })
    ctx.body = {
      code: 200,
      msg: '更新成功'
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      msg: '更新失败'
    }
  }
})
module.exports = UserRouter